<?php
/**店铺信息控制器**/
namespace Admin\Controller;
use User\Api\UserApi;

class ShopController extends AdminController{

	public function lists($p = 1){
        $shop = M("shop");
        $field = "one_shop.id ,one_shop.shop_name, one_shop.shop_addr, m.username, one_type.name";
        $list = $shop->join("LEFT JOIN one_type on one_shop.type_id=one_type.type_id")->join("LEFT JOIN one_ucenter_member m on m.id=one_shop.uid")->field($field)->page($p)->select();
        $count = $shop->count();
        $page = new \Think\Page($count,20);
        $show = $page->show();

        $this->assign("page",$show);
        $this->assign("list",$list);
        $this->meta_title = "店铺列表";
        $this->display();
	}

	public function del($ids=null){
        $ids = array_unique((array)I('ids',0));

        if ( empty($ids) ) {
            $this->error('请选择要操作的数据!');
        }
        $Model = M("shop");
        $map = array('id' => array('in', $ids) );

        $users = $Model->where($map)->select();
        $uids = $users[0]['uid'];
        for($i=1;$i<count($users);$i++){
            $uids .= ",".$users[$i]['uid'];
        }

        if($Model->where($map)->delete() && M("ucenter_member")->where(array('id'=>array('in',$uids)))->delete()){
        // if($Model->where($map)->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }
    
    public function edit($id = 0){
        if(IS_POST){
            $post = $_POST;
            $shop_data = array(
                "id" => $post['id'],
                "shop_name" => $post['shop_name'],
                "shop_addr" => $post['shop_addr'],
                "type_id"   => $post['type_id']
                );
    //         $type_data = array(
    //             "type_id" => $post['type_id'],
    //             "name"    => $post['type_name'],
    //             "shop_cart_image" => $post['cardimage'],
    //             "shop_logo_image" => $post['logo'],
    //             "shop_cart_note" =>$post['shop_cart_note'],
				// "shop_color" =>$post['shop_color'],
    //             "zhutui" => $post['zhutui']
    //             );
            if(M("shop")->save($shop_data)){
                $this->success("修改成功",U('lists'));
            }else{
                $this->error("修改失败".M()->getError());
            }            

        } else {
            // $shopinfo = M("shop")->join("LEFT JOIN one_type on one_type.type_id=one_shop.type_id")->find($id);
            $shopinfo = M("shop")->find($id);
            $shopinfo || $this->error("店铺不存在");

            // 用户
            $username = M("ucenter_member")->getFieldById($shopinfo['uid'],'username');
            $typelist = M("type")->where("is_private=0")->field("type_id,name")->select();

            $this->assign('type',$typelist);
            $this->assign('shopinfo', $shopinfo);
            $this->assign('username', $username);
            $this->meta_title = '店铺编辑';
            $this->display();
        }
    }

    public function add(){
        if(IS_POST){
            $post = $_POST;
            if(empty(trim($post['username'])) || empty(trim($post['shop_name'])) || empty(trim($post['shop_addr']))) $this->error("店铺信息不完整");
            // 总店信息
            if($post['type_id'] == "-1"){
                // 添加新的分类
                if(empty($post['type_name']) || empty($post['logo'])) $this->error("新总店信息不可为空");
                $type_data = array(
                    "name" => $post['type_name'],
                    "shop_cart_image" => empty($post['cardimage'])?$post['logo']:$post['cardimage'],
                    "shop_logo_image" => $post['logo'],
					"shop_color" => $post['shop_color'],
                    "shop_cart_note" =>$post['shop_cart_note'],
                    "zhutui" =>$post['zhutui']
                );
                $rt = $this->add_type($type_data);
                
                if(is_numeric($rt)){
                    $shop_data['type_id'] = $rt;
                }else{
                    $this->error($rt);
                }
            }else if($post['type_id'] > 0){
                $shop_data['type_id'] = $post['type_id'];
            }else{
                $this->error("请先选择所属的总店");
            }

            // 用户信息
            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register(trim($post['username']), "111111","","",2);
            if(0 < $uid){ //注册成功
                $shop_data['uid'] = $uid;
            } else { //注册失败，显示错误信息
                $this->error("注册失败，用户名已存在");
            }

            // 店铺信息
            $shop_data['shop_name'] = $post['shop_name'];
            $shop_data['shop_addr'] = $post['shop_addr'];
            $shop_data['add_uid']   = UID;
            $shop_data['add_time']  = NOW_TIME;
            $shop_data['is_supermarket'] = $post['is_supermarket'];

            if(M('shop')->add($shop_data)){
                $this->success("添加店铺成功",U('lists'));
            }else{
                $this->error(M('shop')->getError());
            }
        } else {
            $typelist = M("type")->where("is_private=0")->field("type_id,name")->select();
            $this->assign("type",$typelist);
            $this->meta_title = '新增店铺';
            $this->display();
        }
    }

    public function typelists($p = 1){
        $list = M("type")->where("is_private=0")->field("type_id,name")->page($p)->select();
        $count = M("type")->where("is_private=0")->count();
        $page = new \Think\Page($count,20);
        $show = $page->show();

        $this->assign("page",$show);
        $this->assign("list",$list);
        $this->meta_title = "总店列表";
        $this->display();
    }

    public function deltype($ids=null){
        $ids = array_unique((array)I('ids',0));
        if ( empty($ids) ) {
            $this->error('请选择要操作的数据!');
        }
        $Model = M("type");
        $map = array('type_id' => array('in', $ids) );

        if($Model->where($map)->delete()){
            $this->success('删除成功');
        } else {
            $this->error('删除失败！');
        }
    }
    public function edittype($id = 0){
        if(IS_POST){
            $post = $_POST;
            $type_data = array(
                "type_id" => $post['type_id'],
                "name"    => $post['name'],
                "shop_cart_image" => $post['cardimage'],
                "shop_logo_image" => $post['logo'],
                "shop_cart_note" =>$post['shop_cart_note'],
                "shop_color" =>$post['shop_color'],
                "zhutui" => $post['zhutui']
                );
            if(M("type")->save($type_data)){
                $this->success("修改成功",U('typelists'));
            }else{
                $this->error("修改失败".M()->getError());
            }  
        }else{
            $type = M("type")->find($id);
            $type || $this->error("总店不存在");

            $this->assign('type', $type);
            $this->meta_title = '总店编辑';
            $this->display();
        }
    }

    protected function add_type($data){
        $type = M("type");
        $r = $type->getFieldByName($data['name'],"type_id");
        if(!$r){
            $ad = $type->add($data);
            return $ad ? $ad:$type->getError();
        }else{
            return "总店名已经存在,不可重复添加";
        }
    }

    public function verson_edit($model = 7, $id = 1){
        // if(IS_POST){
        //     $Model  =   D(parse_name(get_table_name(7),1));
        //     // 获取模型的字段信息
        //     $Model  =   $this->checkAttr($Model,7);
        //     if($Model->create() && $Model->save()){
        //         $this->success('保存成功！');
        //     } else {
        //         $this->error($Model->getError());
        //     }
        // } else {
        //     $fields     = get_model_attribute(7);

        //     //获取数据
        //     $data       = M(get_table_name(7))->find(1);
        //     $data || $this->error('数据不存在！');

        //     $this->assign('model', $model);
        //     $this->assign('fields', $fields);
        //     $this->assign('data', $data);
        //     $this->meta_title = '编辑app版本信息';
        //     $this->display('Think/edit');
        // }
        //获取模型信息
        $model = M('Model')->find($model);
        $model || $this->error('模型不存在！');

        if(IS_POST){
            $Model  =   D(parse_name(get_table_name($model['id']),1));
            // 获取模型的字段信息
            $Model  =   $this->checkAttr($Model,$model['id']);
            if($Model->create() && $Model->save()){
                $this->success('保存'.$model['title'].'成功！');
            } else {
                $this->error($Model->getError());
            }
        } else {
            $fields     = get_model_attribute($model['id']);

            //获取数据
            $data       = M(get_table_name($model['id']))->find($id);
            $data || $this->error('数据不存在！');

            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->assign('data', $data);
            $this->meta_title = '编辑'.$model['title'];
            $this->display();
        }
    }

    protected function checkAttr($Model,$model_id){
        $fields     =   get_model_attribute($model_id,false);
        $validate   =   $auto   =   array();
        foreach($fields as $key=>$attr){
            if($attr['is_must']){// 必填字段
                $validate[]  =  array($attr['name'],'require',$attr['title'].'必须!');
            }
            // 自动验证规则
            if(!empty($attr['validate_rule'])) {
                $validate[]  =  array($attr['name'],$attr['validate_rule'],$attr['error_info']?$attr['error_info']:$attr['title'].'验证错误',0,$attr['validate_type'],$attr['validate_time']);
            }
            // 自动完成规则
            if(!empty($attr['auto_rule'])) {
                $auto[]  =  array($attr['name'],$attr['auto_rule'],$attr['auto_time'],$attr['auto_type']);
            }elseif('checkbox'==$attr['type']){ // 多选型
                $auto[] =   array($attr['name'],'arr2str',3,'function');
            }elseif('date' == $attr['type']){ // 日期型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }elseif('datetime' == $attr['type']){ // 时间型
                $auto[] =   array($attr['name'],'strtotime',3,'function');
            }
        }
        return $Model->validate($validate)->auto($auto);
    }

}
?>